var express = require("express");
var app = express();

var MongoClient = require("mongodb").MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/";

// solve cross-domain issues
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Method", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Max-Age", "3600");
  next();
});

var _xxObj = {
  arrs: [
    {
      id: "n1",
      name: "a_name",
      vals: "aaa",
    },
    {
      id: "n2",
      name: "b_name",
      vals: "bbb",
    },
    {
      id: "n3",
      name: "c_name",
      vals: "ccc",
    },
  ],
};

var filterResult = null;

function filter(_val) {
  return _xxObj.arrs.filter((_g) => {
    return _g.vals === _val;
  });
}

app.get("/node_a", function (req, res) {
  //   console.log("xxx start");
  let _result = filter(req.query.v_data);
  filterResult =
    _result.length !== 0 ? _result : [{ id: "xxx", name: "not found" }];
  res.end();
});

app.get("/node_b", function (req, res) {
  res.send(filterResult);
});

app.post("/register_post", function (req, res) {
  let _allData = "";
  req.on("data", function (_d) {
    _allData += _d;
  });
  req.on("end", function () {
    // console.log(_allData);
    let _regsObj = JSON.parse(_allData);
    findSameNameFn(_regsObj, res);
    // insertNewUser();
  });
});

function findSameNameFn(_regsObj, res) {
  MongoClient.connect(DB_CONN_STR, function (err, db) {
    var _dbo = db.db("proShopCart");
    var _collection = _dbo.collection("userInfo");
    _collection.findOne(
      { username: _regsObj.username },
      {},
      function (err, result) {
        if (err) throw err;
        if (result === null) {
          // console.log("no same name");
          insertNewUser(_regsObj, res);
        } else if (result.username === _regsObj.username) {
          console.log("duplicate name");
          res.send({
            regsInfo: "名字已存在",
            regs_code: 2,
          });
        }
        db.close();
      }
    );
  });
}

function insertNewUser(_insertObj, res) {
  MongoClient.connect(DB_CONN_STR, function (err, db) {
    var _dbo = db.db("proShopCart");
    var _collection = _dbo.collection("userInfo");
    _collection.insertOne(_insertObj, function (err, result) {
      if (err) throw err;
      console.log("注册成功");
      res.send({
        regsInfo: "注册成功",
        regs_code: 1,
      });
      db.close();
    });
  });
}

app.post("/login_post", function (req, res) {
  var _loginObj = "";
  req.on("data", function (_d) {
    _loginObj += _d;
  });
  req.on("end", function (_d) {
    // console.log(_loginObj);
    let _item = JSON.parse(_loginObj);
    MongoClient.connect(DB_CONN_STR, function (err, db) {
      var _dbo = db.db("proShopCart");
      var _collection = _dbo.collection("userInfo");
      _collection.findOne(
        { username: _item.username },
        {},
        function (err, result) {
          if (err) throw err;
          if (result === null) {
            // console.log("用户不存在");
            return res.send({
              regsInfo: "用户不存在",
              regs_code: 4,
            });
          } else if (_item.password !== result.password) {
            // console.log("密码错误")
            return res.send({
              regsInfo: "密码错误",
              regs_code: 5,
            });
          } else if (result !== null && _item.password === result.password) {
            // console.log("登录成功");
            return res.send({
              regsInfo: result,
              regs_code: 3,
            });
          }

          db.close();
        }
      );
    });
  });
});

app.post("/insertGoods", function (req, res) {
  var _dataObj = "";
  req.on("data", function (_d) {
    _dataObj += _d;
  });
  req.on("end", function (_d) {
    let _insertGoodsArrsObj = JSON.parse(_dataObj);
    // console.log(_insertGoodsArrsObj);
    MongoClient.connect(DB_CONN_STR, function (err, db) {
      var _dbo = db.db("proShopCart");
      var _collection = _dbo.collection("goodsCategory");
      _collection.insertMany(_insertGoodsArrsObj, function (err, result) {
        if (err) throw err;
        res.send({
          regsInfo: "商品录入成功",
          regs_code: 5,
        });
        db.close();
      });
    });
  });
});

app.get("/getGoodsCategory", function (req, res) {
  MongoClient.connect(DB_CONN_STR, function (err, db) {
    var _dbo = db.db("proShopCart");
    var _collection = _dbo.collection("goodsCategory");
    _collection
      .aggregate([
        {
          $lookup: {
            localField: "d",
            from: "goodsList_a",
            foreignField: "category",
            as: "goodsList_aa",
          },
        },
        {
          $lookup: {
            localField: "d",
            from: "goodsList_b",
            foreignField: "category",
            as: "goodsList_bb",
          },
        },
        {
          $lookup: {
            localField: "d",
            from: "goodsList_c",
            foreignField: "category",
            as: "goodsList_cc",
          },
        },
        {
          $lookup: {
            localField: "d",
            from: "goodsList_d",
            foreignField: "category",
            as: "goodsList_dd",
          },
        },
      ])
      .toArray(function (err, result) {
        if (err) throw err;
        return res.send(result);
        db.close();
      });
  });
});

app.get("/getGoodsInfo", function (req, res) {
  var _findId = req.query._id;
  var _c = req.query._c;
  var ObjectID = require("mongodb").ObjectID;
  var _findObjId = ObjectID.createFromHexString(_findId);

  MongoClient.connect(DB_CONN_STR, function (err, db) {
    var _dbo = db.db("proShopCart");
    var _collection = _dbo.collection(_c);
    _collection.findOne({ _id: _findObjId }, {}, function (err, result) {
      if (err) throw err;
      res.send(result);
      db.close();
    });
  });
});

app.get("/getGoodsCategoryListFn", function (req, res) {
  var _c = req.query.categoryId;

  MongoClient.connect(DB_CONN_STR, function (err, db) {
    var _dbo = db.db("proShopCart");
    var _collection = _dbo.collection(_c);
    _collection.find().toArray(function (err, result) {
      if (err) throw err;
      return res.send(result);
      db.close();
    });
  });
});

app.get("/getpageChange", function (req, res) {
  var _s = req.query.startNum;
  var _c = req.query.c;
  if (Number(_s) < 0) {
    _s = 0;
  }
  MongoClient.connect(DB_CONN_STR, function (err, db) {
    var _dbo = db.db("proShopCart");
    var _collection = _dbo.collection(_c);
    _collection
      .find()
      .limit(2)
      .skip(Number(_s))
      .toArray(function (err, result) {
        if (err) throw err;
        return res.send(result);
        db.close();
      });
  });
});

app.get("/getImgUrls", function (req, res) {
  let imgObj = {
    urls: [
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F035%2F063%2F726%2F3ea4031f045945e1843ae5156749d64c.jpg&refer=http%3A%2F%2Fyouimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623934036&t=2b6b8bb64dee3080d46e5d96d9acc19e",
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2F1812.img.pp.sohu.com.cn%2Fimages%2Fblog%2F2009%2F11%2F18%2F18%2F8%2F125b6560a6ag214.jpg&refer=http%3A%2F%2F1812.img.pp.sohu.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623934036&t=6a66a49129a749d4de60ef8c4fe15994",
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F4c%2Fa6%2F31%2F4ca631a8841304be2351295d50cf801d.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623934036&t=435747a754ea2c2b2c8937c0c885938d",
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F004%2F531%2F381%2F4339f96900344574a0c8ca272a7b8f27.jpg&refer=http%3A%2F%2Fyouimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623934036&t=b489576459d61444e23ee538fb0663e0",
    ],
  };
  return res.send(imgObj);
});

function insertGoodsList() {
  let goodsListObj = [
    {
      name: "洗衣机",
      price: 22,
      category: "goodsList_b",
      img: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548497575095&di=d4a59272c4cf53848d8b615f208a4d38&imgtype=0&src=http%3A%2F%2Fimg010.hc360.cn%2Fk1%2FM01%2F30%2F25%2F4LLd34735d9f8e3092065fBff467C42d385.png",
      describe: " 洗衣机特好，洗的干净",
    },
    {
      name: "燃气灶",
      price: 33,
      category: "goodsList_b",
      img: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548497592730&di=21f41bd6f1ddf4178951c7cc1a59515f&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fhousephotolib%2F1610%2F13%2Fc1%2F28285254_1476289213390_690x460.jpg",
      describe: " 燃气灶特好，火大",
    },
    {
      name: "冰箱",
      price: 44,
      category: "goodsList_b",
      img: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548497740253&di=2a66cd86af34128a3160f36597a7b4f8&imgtype=0&src=http%3A%2F%2Fpic15.photophoto.cn%2F20100610%2F0020033085457192_b.jpg",
      describe: " 冰箱特好，凉",
    },
    {
      name: "空调",
      price: 55,
      category: "goodsList_b",
      img: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548497798102&di=43fb38fe2fd46d41dab6e4e9ecd66e06&imgtype=0&src=http%3A%2F%2Fsc.jb51.net%2Fuploads%2Fallimg%2F140416%2F11-14041610514b17.jpg",
      describe: " 空调特好，冻死个人",
    },
  ];

  MongoClient.connect(DB_CONN_STR, function (err, db) {
    var _dbo = db.db("proShopCart");
    var _collection = _dbo.collection("goodsList_b");
    _collection.insertMany(goodsListObj, function (err, result) {
      if (err) throw err;
      db.close();
    });
  });
}
// insertGoodsList();

app.listen(8888, function () {
  console.log("8888server running");
});
